package com.dhms.vostok1.network

import android.content.Intent
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.dhms.lib.app.LibApplication
import com.dhms.vostok1.constant.ErrorCode.Companion.UN_AUTHORIZED
import com.dhms.vostok1.constant.StringCode.Companion.TOKEN_EXPIRED_BROADCAST_NAME
import okhttp3.Interceptor
import okhttp3.Response

class ResponseInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)

        if (response.code == UN_AUTHORIZED) {
            LibApplication.getAppContext()?.let {
                LocalBroadcastManager.getInstance(it)
                    .sendBroadcast(TOKEN_EXPIRED_BROADCAST_INTENT)
            }
        }
        return response
    }

    companion object {
        val TOKEN_EXPIRED_BROADCAST_INTENT by lazy {
            Intent(TOKEN_EXPIRED_BROADCAST_NAME)
        }
    }
}